package com.appcloner.data.local.datastore

import android.content.Context
import androidx.datastore.preferences.core.*
import androidx.datastore.preferences.preferencesDataStore
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton

private val Context.dataStore by preferencesDataStore(name = "app_preferences")

@Singleton
class AppPreferences @Inject constructor(
    @ApplicationContext private val context: Context
) {
    private val dataStore = context.dataStore
    
    companion object {
        private val CARD_KEY = stringPreferencesKey("card_key")
        private val CARD_EXPIRES_AT = longPreferencesKey("card_expires_at")
        private val CARD_PERMISSION_LEVEL = intPreferencesKey("card_permission_level")
        private val DEVICE_ID = stringPreferencesKey("device_id")
        private val LANGUAGE = stringPreferencesKey("language")
    }
    
    suspend fun saveCardInfo(cardKey: String, expiresAt: Long, permissionLevel: Int) {
        dataStore.edit { preferences ->
            preferences[CARD_KEY] = cardKey
            preferences[CARD_EXPIRES_AT] = expiresAt
            preferences[CARD_PERMISSION_LEVEL] = permissionLevel
        }
    }
    
    suspend fun getSavedCardKey(): String {
        return dataStore.data.map { it[CARD_KEY] ?: "" }.first()
    }
    
    suspend fun getCardExpiresAt(): Long {
        return dataStore.data.map { it[CARD_EXPIRES_AT] ?: 0L }.first()
    }
    
    suspend fun getCardPermissionLevel(): Int {
        return dataStore.data.map { it[CARD_PERMISSION_LEVEL] ?: 0 }.first()
    }
    
    suspend fun getDeviceId(): String {
        val deviceId = dataStore.data.map { it[DEVICE_ID] }.first()
        if (deviceId.isNullOrEmpty()) {
            val newDeviceId = generateDeviceId()
            dataStore.edit { preferences ->
                preferences[DEVICE_ID] = newDeviceId
            }
            return newDeviceId
        }
        return deviceId
    }
    
    suspend fun setLanguage(language: String) {
        dataStore.edit { preferences ->
            preferences[LANGUAGE] = language
        }
    }
    
    suspend fun getLanguage(): String {
        return dataStore.data.map { it[LANGUAGE] ?: "zh" }.first()
    }
    
    private fun generateDeviceId(): String {
        return "device_${System.currentTimeMillis()}_${(1000..9999).random()}"
    }
}
